package cn.itsource.order.service.impl;

import cn.itsource.basic.constant.BusinessConstant;
import cn.itsource.basic.domain.Point;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.CodeGenerateUtils;
import cn.itsource.basic.util.DistanceUtil;
import cn.itsource.order.domain.OrderAddress;
import cn.itsource.order.domain.ProductOrder;
import cn.itsource.order.domain.ProductOrderDetail;
import cn.itsource.order.mapper.OrderAddressMapper;
import cn.itsource.order.mapper.ProductOrderDetailMapper;
import cn.itsource.order.mapper.ProductOrderMapper;
import cn.itsource.order.service.IProductOrderService;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pay.domain.AlipayInfo;
import cn.itsource.pay.domain.PayBill;
import cn.itsource.pay.mapper.AlipayInfoMapper;
import cn.itsource.pay.mapper.PayBillMapper;
import cn.itsource.pay.service.IPayBillService;
import cn.itsource.product.domain.Product;
import cn.itsource.product.mapper.ProductMapper;
import cn.itsource.quartz.config.MainJob;
import cn.itsource.quartz.domain.QuartzInfo;
import cn.itsource.quartz.service.IQuartzService;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.UserAddress;
import cn.itsource.user.mapper.UserAddressMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private IQuartzService quartzService;
    /*参数 map {productId=66, addressId=1, payId=1}
        生成订单的时候 操作的表
        t_order_product

        t_order_product_detail
        t_order_address

       实现步骤：
        1.生成 服务订单表的数据 t_order_product


        2.生成 服务订单详情 t_order_product_detail


        3.生成 服务地址表 t_order_address

        4.根据订单 生成支付单 t_pay_bill


        5.调用的支付宝的支付接口，拉取收银台

     */
    @Override
    @Transactional
    public String createOrder(Map<String, String> map,User user) {
        Long  productId = Long.valueOf(map.get("productId"));
        Long  addressId = Long.valueOf(map.get("addressId"));
        Product product = productMapper.loadOne(productId);
        //用户选择的地址
        UserAddress userAddress = userAddressMapper.loadOne(addressId);
        //1.生成 服务订单表的数据 t_order_product
        ProductOrder productOrder = createProductOrder(product,user,userAddress);
        productOrderMapper.save(productOrder);

        //2.生成 服务订单详情 t_order_product_detail
        ProductOrderDetail productOrderDetail = createProductOrderDetail(product);
        productOrderDetail.setOrder_id(productOrder.getId());

        productOrderDetailMapper.save(productOrderDetail);
        //3.生成 服务地址表 t_order_address
        OrderAddress orderAddress = createOrderAddress(userAddress);
        //设置关联信息
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        orderAddressMapper.save(orderAddress);

        //4.生成支付单
        PayBill payBill = createPayBill(productOrder);
        //保存订单
        payBillMapper.save(payBill);
        //----------------------添加定时任务--------------
        QuartzInfo quartzInfo = new QuartzInfo();
         //每一个任务都有唯一的名字
        quartzInfo.setJobName("product"+productOrder.getOrderSn());
        //当前定时任务的执行的逻辑代码
        quartzInfo.setCla(MainJob.class);
        //最后的支付时间 检查订单状态
        quartzInfo.setTime(productOrder.getLastPayTime());
        //
        Map<String,Object> params = new HashMap<>();
        params.put("orderSn", productOrder.getOrderSn());
        //设置定时任务的参数
        quartzInfo.setParams(params);

        quartzService.addJob(quartzInfo);
        //-----------------------------------------------
        AlipayInfo alipayInfo= alipayInfoMapper.queryByShopId(payBill.getShop_id());
        //5.提交支付数据
        String result = payBillService.paySubmit(alipayInfo,payBill);
        return result;

    }

    private PayBill createPayBill(ProductOrder productOrder){
        PayBill payBill = new PayBill();
        /*
            private String digest;
            private BigDecimal money;
            private String unionPaySn;//支付单号
            private Integer state;
            private Date lastPayTime;
            private Long payChannel; //0 余额 1 支付宝 2 微信 3 银联
            private String businessType;
            private Long businessKey;
            private Date updateTime;
            private Date createTime;
            private Long user_id;
            private Long shop_id;
            private String nickName;

         */
        payBill.setDigest(productOrder.getDigest());
        payBill.setMoney(productOrder.getPrice());
        payBill.setState(0);//待支付
        payBill.setLastPayTime(productOrder.getLastPayTime());
        payBill.setPayChannel(1L);
        payBill.setCreateTime(new Date());
        payBill.setUser_id(productOrder.getUser_id());
        payBill.setShop_id(productOrder.getShop_id());
        //业务类型
        payBill.setBusinessType(BusinessConstant.PRODUCT_ORDER);
        //业务主键
        payBill.setBusinessKey(productOrder.getId());
        payBill.setOrderSn(productOrder.getOrderSn());
        return payBill;
    }

    //创建OrderAddress  t_order_address
    private OrderAddress createOrderAddress(UserAddress userAddress){
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);

        return orderAddress;
    }

    //t_order_product_detail
    private ProductOrderDetail createProductOrderDetail(Product product){
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
       /*
        private Long order_id;
        */
        //数据的拷贝
        BeanUtils.copyProperties(product, productOrderDetail);
        productOrderDetail.setProduct_id(product.getId());
        return productOrderDetail;
    }


    private ProductOrder createProductOrder( Product product,User user,UserAddress userAddress){
        ProductOrder productOrder = new ProductOrder();
        /*
        private String digest;
        private Integer state;
        private BigDecimal price;
        private String orderSn;
        private String paySn;
        private Date lastPayTime;
        private Date lastConfirmTime;
        private Long product_id;
        private Long user_id;
        private Long shop_id;  //分配
        private Long address_id;
         */
        productOrder.setDigest("[服务订单]"+product.getName());
        productOrder.setState(0);
        productOrder.setPrice(product.getSaleprice());
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        //计算当前时间的30分钟过后的Date对象
        Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 2);
        productOrder.setLastPayTime(date);
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());

        //计算用户地址的经纬度
        Point point = DistanceUtil.getPoint(userAddress.getFullAddress());
        List<Shop> shops = shopMapper.loadAll();
        //计算最近的门店
        Shop shop = DistanceUtil.getNearestShop(point, shops);

        productOrder.setShop_id(shop.getId());
        return productOrder;
    }
}
